package com.ruoyi.system.controller;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.security.SignatureException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.BiaoBeiTts;
import com.ruoyi.framework.web.service.TtsClientApp;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.MingProdinfo;
import com.ruoyi.system.service.IMingProdinfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 产品详情Controller
 * 
 * @author ruoyi
 * @date 2022-02-26
 */
@RestController
@RequestMapping("/system/prodinfo")
public class MingProdinfoController extends BaseController
{
    @Autowired
    private IMingProdinfoService mingProdinfoService;

//    @Autowired
//    private TtsClientApp ttsClientApp;

    private int [] boxSize = {50,100,200,400,800,1600,3200};
//    private int [] boxSize = {5,10,20,40,80,160,320};

    private int ttsType = 1; //0 讯飞  1 标贝

    /**
     * 查询产品详情列表
     */
    @PreAuthorize("@ss.hasPermi('system:prodinfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(MingProdinfo mingProdinfo)
    {
        startPage();
        List<MingProdinfo> list = mingProdinfoService.selectMingProdinfoList(mingProdinfo);
        return getDataTable(list);
    }

    /**
     * 导出产品详情列表
     */
    @PreAuthorize("@ss.hasPermi('system:prodinfo:export')")
    @Log(title = "产品详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MingProdinfo mingProdinfo)
    {
        List<MingProdinfo> list = mingProdinfoService.selectMingProdinfoList(mingProdinfo);
        ExcelUtil<MingProdinfo> util = new ExcelUtil<MingProdinfo>(MingProdinfo.class);
        util.exportExcel(response, list, "产品详情数据");
    }

    /**
     * 获取产品详情详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:prodinfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(mingProdinfoService.selectMingProdinfoById(id));
    }

    /**
     * 新增产品详情
     */
    @PreAuthorize("@ss.hasPermi('system:prodinfo:add')")
    @Log(title = "产品详情", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MingProdinfo mingProdinfo)
    {
        //纸箱大于指定值时 将自动触发移动操作
        if (null != mingProdinfo.getCurrSize()) {
            if (mingProdinfo.getCurrSize() > boxSize[0]) {
                MingProdinfo mingProdinfo2 = mingProdinfo;
                //移动到第二宝箱
                mingProdinfoService.updateMingProdinfoClassid(mingProdinfo2);
                List<MingProdinfo> mps = mingProdinfoService.selectMingProdinfoSize(mingProdinfo2);
                for (MingProdinfo mpi : mps) {
                    if (mpi.getCurrSize() >= boxSize[mpi.getClassid() - 1]) {
                        mingProdinfo2.setClassid(mpi.getClassid() - 1);
                        mingProdinfoService.updateMingProdinfoClassid(mingProdinfo2);
                    }
                }
            }
        }
        return toAjax(mingProdinfoService.insertMingProdinfo(mingProdinfo));
    }

    /**
     * 生成mp3
     */
    @PreAuthorize("@ss.hasPermi('system:prodinfo:edit')")
    @Log(title = "生成mp3文件", businessType = BusinessType.UPDATE)
    @PostMapping("/createMp3")
    public AjaxResult createMp3(@RequestBody MingProdinfo mingProdinfo)
    {
        try {
            MingProdinfo mingProdinfoNew = mingProdinfoService.selectMingProdinfoById(mingProdinfo.getId());
            String newContent = "";
            //增加词组停顿
            if (StringUtils.isNotBlank(mingProdinfoNew.getMydesc())) {
                String [] arr = mingProdinfoNew.getMydesc().split("\n");
                if (null == arr || arr.length ==0) {
                    return AjaxResult.error("词组数量为空");
                }
                int playtime = 1;
                int waittime = 0;
                if (null!=mingProdinfo.getPlaytime()&&null!=mingProdinfo.getWaittime()) {
                    playtime = mingProdinfo.getPlaytime();
                    waittime = mingProdinfo.getWaittime()*1000;
                }
                List<String> list = Arrays.asList(arr);

                if (null != mingProdinfo.getLuanxu() && mingProdinfo.getLuanxu()>0) {
//                    list = Arrays.asList(arr);
                    //乱序
                    Collections.shuffle(list);
                }

                int num = 1;
                String mp3word = "";
                for (String word: list) {
                    if (mingProdinfo.getChouchanum()>0&&num>mingProdinfo.getChouchanum()) {
                        break;
                    }
                    mp3word +=word+"; ";
                    num++;
                    for (int i=0;i<playtime;i++) {
                        if (waittime>0) {
                            if (ttsType==0) {
                                newContent += word + "<break time=\"" + waittime + "\"/>";
                            } else {
                                newContent += word + "<silence len=" + waittime + ">";
                            }
                        } else {
                            newContent += word;
                        }
                    }
                }

                mingProdinfoNew.setPlaytime(mingProdinfo.getPlaytime());
                mingProdinfoNew.setWaittime(mingProdinfo.getWaittime());
                mingProdinfoNew.setSpeed(mingProdinfo.getSpeed());
                mingProdinfoNew.setLuanxu(mingProdinfo.getLuanxu());
                mingProdinfoNew.setChouchanum(mingProdinfo.getChouchanum());
                mingProdinfoNew.setMp3word(mp3word);
                mingProdinfoService.updateMingProdinfo(mingProdinfoNew);
                logger.info(newContent);
            }

            if (StringUtils.isNotBlank(newContent)) {
                if (ttsType==0) {
                    TtsClientApp ttsClientApp = new TtsClientApp();
                    ttsClientApp.createMp3(mingProdinfoNew.getId().toString(), newContent,mingProdinfo.getSpeed());
                } else {
                    BiaoBeiTts.mkMp3ByBb(mingProdinfoNew.getId().toString(), newContent, mingProdinfo.getSpeed());
                }
            } else {
                return AjaxResult.error("生成mp3错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success("ok");
    }

    /**
     * 修改产品详情
     */
    @PreAuthorize("@ss.hasPermi('system:prodinfo:edit')")
    @Log(title = "产品详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MingProdinfo mingProdinfo)
    {
        return toAjax(mingProdinfoService.updateMingProdinfo(mingProdinfo));
    }

    @PreAuthorize("@ss.hasPermi('system:prodinfo:edit')")
    @Log(title = "更新宝箱", businessType = BusinessType.UPDATE)
    @PostMapping("/editClassid")
    public AjaxResult editClassid(@RequestBody MingProdinfo mingProdinfo)
    {
        return toAjax(mingProdinfoService.updateMingProdinfoClassid(mingProdinfo));
    }

    /**
     * 删除产品详情
     */
    @PreAuthorize("@ss.hasPermi('system:prodinfo:remove')")
    @Log(title = "产品详情", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mingProdinfoService.deleteMingProdinfoByIds(ids));
    }
}
